// pages/order/orderConfirmOne/orderConfirmOne.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    work_order_id: '', //工单id
    type: '', //数据类型 1试用,2改造
    code: '',//测试单编码
    stove_number: '',//炉具改造数量

    typeList: [], //炉具类型列表

    cookerArr: [{ stoves_code: '', cooker_type: '', index: '',comprehensive_hour1:'',comprehensive_minute1:'',comprehensive_second1:'',comprehensive_gas_consumption1:'', minute1: '', second1: '', gas_consumption1: '',comprehensive_hour2:"",comprehensive_minute2:'', minute2: '', comprehensive_second2:'',hour1:'',hour2:'',second2: '',comprehensive_gas_consumption2:'', gas_consumption2: '', scale: '',comprehensive_scale:'',open:true}], //炉具基本信息

    // custodyList: [], //保管清单
    // allTotalPrice: 0, //清单总价
    isShow:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      work_order_id: options.work_order_id,
      type: options.type,
      code: options.code,
      stove_number: options.stove_number,
    })
    that.geTypeList(); //获取炉具类型
    
    // 看是否有缓存,如果有直接回显;没有就获取确认单详情(或者代表直接新增)
    var key = 'confirmData_' + that.data.work_order_id;
    var confirmData = wx.getStorageSync(key) || '';
    if (confirmData) {
      that.setData({
        cookerArr: confirmData.cookerArr, //炉具基本信息
        // custodyList: confirmData.custodyList, //保管清单
        // allTotalPrice: confirmData.allTotalPrice, //清单总价
      })
    } else {
      // that.geCustodyList(); //获取炉具清单
      that.getInfo();//获取确认单详情
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // console.log(123,'onshow')
    // //返回上级页面询问弹窗
    // const version = wx.getSystemInfoSync().SDKVersion;
    // if (app.compareVersion(version, '2.12.0') >= 0) {
    //   wx.enableAlertBeforeUnload({
    //     message: '是否保存本页数据?',
    //     success(res) {
    //       //console.log(123, res)
    //     },
    //     fail(fail) {

    //     }
    //   })
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  onUnload: function () {
    // this.save();//保存数据
    // console.log(123,'页面卸载')
  },
  //收起展开
  openFun(e){
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr[index].open = !cookerArr[index].open;
    this.setData({ cookerArr });
  },

  //获取炉具类型
  geTypeList() {
    var that = this;
    app.ajax({
      url: 'Common/Common/getStoveConfig',
      data: {},
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            typeList: res.data.data
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //选择炉具类型
  bindTypePicker(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr[index].index = e.detail.value;
    cookerArr[index].cooker_type = this.data.typeList[e.detail.value].id;
    this.setData({ cookerArr });
  },
  //炉具基本信息输入
  inputCooker(e){
    let { index,name } = e.currentTarget.dataset;
    let obj = 'cookerArr['+ index +'].'+name;
    this.setData({ 
      [obj]: e.detail.value
    })
  },
  //炉具改造节能比例计算
  countScale(e){
    let { index } = e.currentTarget.dataset;
    if (this.data.cookerArr[index].gas_consumption1){
      let scale = (this.data.cookerArr[index].gas_consumption1 - this.data.cookerArr[index].gas_consumption2) / this.data.cookerArr[index].gas_consumption1 * 100;
      let obj = 'cookerArr[' + index + '].scale';
      this.setData({
        [obj]: scale.toFixed(2)
      })
    }
  },
    //综合节能炉具改造节能比例计算
    comprehensive_countScale(e){
      let { index } = e.currentTarget.dataset;
      if (this.data.cookerArr[index].comprehensive_gas_consumption1){
        let comprehensive_scale = (this.data.cookerArr[index].comprehensive_gas_consumption1 - this.data.cookerArr[index].comprehensive_gas_consumption2) / this.data.cookerArr[index].comprehensive_gas_consumption1 * 100;
        let obj = 'cookerArr[' + index + '].comprehensive_scale';
        this.setData({
          [obj]: comprehensive_scale.toFixed(2)
        })
      }
    },
  //添加炉具
  addCookerBtn() {
    var cookerArr = this.data.cookerArr;
    if (cookerArr.length > 99) {
      return false;
    }
    //炉具基本信息
    var obj = { stoves_code: '', cooker_type: '', index: '',comprehensive_minute1:'',comprehensive_second1:'',comprehensive_gas_consumption1:'', minute1: '', second1: '', gas_consumption1: '',comprehensive_minute2:'', minute2: '', comprehensive_second2:'',second2: '',comprehensive_gas_consumption2:'', gas_consumption2: '', scale: '',comprehensive_scale:'',open:true, hour1:'',hour2:'',comprehensive_hour1:'',comprehensive_hour2:''};
  
    cookerArr.push(obj);
    this.setData({ cookerArr })
  },
  //删除炉具
  cutCookerBtn(e) {
    let { index } = e.currentTarget.dataset;
    let cookerArr = this.data.cookerArr;
    cookerArr.splice(index, 1);
    this.setData({ cookerArr })
  },

  //获取炉具清单
  geCustodyList() {
    var that = this;
    app.ajax({
      url: 'Common/Common/getServiceConfig',
      method: "POST",
      data: { key: 'custody_list'},
      success: function (res) {
        if (res.data.code == 1000) {
          var list = res.data.data;
          list.forEach((item,i)=>{
            item.num = 0;
            item.totalPrice = 0;
          })
          that.setData({
            custodyList: list
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  // 增加数量
  addCount(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var num = Number(that.data.custodyList[index].num);
    num = num + 1;
    var obj_m = 'custodyList[' + index + '].num';
    var price = that.data.custodyList[index].price * num;
    var obj_p = 'custodyList[' + index + '].totalPrice';
    that.setData({
      [obj_m]: num,
      [obj_p]: price.toFixed(2)
    });
    that.getTotalPrice();
  },
  // 输入数量
  cookerNumInput(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var num = e.detail.value;
    var obj_m = 'custodyList[' + index + '].num';
    var price = Number(that.data.custodyList[index].price) * num;
    var obj_p = 'custodyList[' + index + '].totalPrice';
    that.setData({
      [obj_m]: num,
      [obj_p]: price.toFixed(2)
    });
    that.getTotalPrice();
  },
  // 失去焦点时
  blurInput(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var num = e.detail.value;
    var obj_m = 'custodyList[' + index + '].num';
    var price = Number(that.data.custodyList[index].price) * num;
    var obj_p = 'custodyList[' + index + '].totalPrice';
    that.setData({
      [obj_m]: num,
      [obj_p]: price.toFixed(2)
    });
    that.getTotalPrice();
  },
  // 减少数量
  delCount(e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var num = Number(that.data.custodyList[index].num);
    if (num<=0){
      return
    }
    num = num - 1;
    var obj_m = 'custodyList[' + index + '].num';
    var price = that.data.custodyList[index].price * num;
    var obj_p = 'custodyList[' + index + '].totalPrice';
    that.setData({
      [obj_m]: num,
      [obj_p]: price.toFixed(2)
    });
    that.getTotalPrice();
  },
  // 计算总价格
  getTotalPrice() {
    var that = this;
    var lists = that.data.custodyList;
    var total = 0;
    lists.forEach((item,index)=>{
      total += Number(item.totalPrice);
    })
    this.setData({
      allTotalPrice: total.toFixed(2)
    });
  },

  //提交数据
  submit(){
    var that = this;
    var cando = true;
    //炉具
    var cookerArr = that.data.cookerArr;
    var data = [];
    cookerArr.forEach((item,index) => {
      if (item.cooker_type == '') {
        app.showToast('请选择第' + (index+1) + '个炉具类别');
        cando = false;
        return false;
      }
      if (item.stoves_code == ''){
        app.showToast('请输入第' + (index+1) + '个炉具编码');
        cando = false;
        return false;
      }
      var _obj = {
        stoves_code: item.stoves_code,
        cooker_name: item.cooker_type,
        test_method: that.data.typeList[item.index||0].water_quantity,
        before_testing_h: item.hour1||0,
        before_testing_i: item.minute1||0,
        before_testing_s: item.second1 || 0,
        before_testing_gas_consumption: item.gas_consumption1,
        after_testing_h: item.hour2||0,
        after_testing_i: item.minute2||0,
        after_testing_s: item.second2 || 0,
        after_testing_gas_consumption: item.gas_consumption2,
        comprehensive_before_testing_h:item.comprehensive_hour1 || 0,
        comprehensive_before_testing_i:item.comprehensive_minute1 || 0,
        comprehensive_before_testing_s:item.comprehensive_second1 || 0,
        comprehensive_before_testing_gas_consumption:item.comprehensive_gas_consumption1 || '',
        comprehensive_after_testing_h:item.comprehensive_hour2 || 0,
        comprehensive_after_testing_i:item.comprehensive_minute2 || 0,
        comprehensive_after_testing_s: item.comprehensive_second2 || 0,
        comprehensive_after_testing_gas_consumption:item.comprehensive_gas_consumption2 || '',
        array_id: item.array_id || '',
        is_confirm: item.is_confirm,
        confirm_time: item.confirm_time,
      };
      data.push(_obj);
      console.log(123,data)
      return;
    })
    if (cando == false) {
      return false;
    }
    app.ajax({
      url: 'Engineer/Workorder/addTestDataCooker',
      method: "POST",
      data: { 
        work_order_id: that.data.work_order_id,
        work_order_type: that.data.type,
        data: data,
      },
      success: function (res) {
        if (res.data.code == 1000) {
          var _key = 'confirmData_' + that.data.work_order_id;
          wx.removeStorageSync(_key);
          app.showToast(res.data.message);
          setTimeout(()=>{
            wx.navigateBack();
          },1000);
        } else if (res.data.code == 2001) {//低于30%处理
          that.againConfirm(res.data.message, data);
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //节能比例低于30%的确认弹窗
  againConfirm(message,_data){
    var that = this;
    wx.showModal({
      title: message,
      content: '请选择修正数据或是关闭工单',
      cancelText: '修正数据',
      confirmText: '关闭工单',
      success(res) {
        if (res.confirm) {
          //关闭
          app.ajax({
            url: 'Engineer/Workorder/closeWorkOrder',
            method: "POST",
            data: {
              work_order_id: that.data.work_order_id,
              cooker_data: _data,
            },
            success: function (res) {
              if (res.data.code == 1000) {
                app.showToast('工单已关闭');
                setTimeout(() => {
                  wx.navigateBack();
                }, 1000)
              } else {
                app.showToast(res.data.message);
              }
            }
          })
        } else if (res.cancel) {
          //取消继续修改
        }
      }
    })
  },

  //保存,缓存数据
  save(){
    var that = this;
    var _key = 'confirmData_' + that.data.work_order_id;
    var _data = {
      cookerArr: that.data.cookerArr, //炉具基本信息
    };
    wx.setStorageSync(_key, _data);
    app.showToast('保存成功');
    wx.disableAlertBeforeUnload();
  },

  //获取确认单详情
  getInfo(){
    var that = this;
    var type = 1;//1、测试确认单、2保管清单、3分享确认单
    var work_order_type = that.data.type;//1试用2改造
    app.ajax({
      url: 'Engineer/Workorder/testDataCookerDetail',
      method: "POST",
      data: {
        work_order_id: that.data.work_order_id,
        type: type,
        work_order_type: work_order_type,
      },
      success: function (res) {
        if (res.data.code == 1000) {
          var cookerArr = [];
          var cooker_list = res.data.data.cooker_data;
          cooker_list.forEach((item,index) => {
            var type_index = '';
            that.data.typeList.forEach((i_te,ind) => {
              if (i_te.id == item.cooker_name){
                type_index = ind;
              }
            })
            var _obj = {
              stoves_code: item.stoves_code,
              cooker_type: item.cooker_name,
              index: type_index,
              water_quantity: item.test_method,
              hour1: item.before_testing_h,
              minute1: item.before_testing_i,
              second1: item.before_testing_s,
              gas_consumption1: item.before_testing_gas_consumption,
              hour2: item.after_testing_h,
              minute2: item.after_testing_i,
              second2: item.after_testing_s,
              gas_consumption2: item.after_testing_gas_consumption,
              scale: item.energy_saving_ratio,
              comprehensive_hour1:item.comprehensive_before_testing_h,
              comprehensive_minute1:item.comprehensive_before_testing_i,
              comprehensive_second1:item.comprehensive_before_testing_s,
              comprehensive_gas_consumption1:item.comprehensive_before_testing_gas_consumption,
              comprehensive_hour2:item.comprehensive_after_testing_h,
              comprehensive_minute2:item.comprehensive_after_testing_i,
              comprehensive_second2:item.comprehensive_after_testing_s,
              comprehensive_gas_consumption2:item.comprehensive_after_testing_gas_consumption,
              comprehensive_scale:item.comprehensive_energy_saving_ratio,
              is_confirm: item.is_confirm,
              confirm_time: item.confirm_time,
              array_id: item.array_id,
            };
            cookerArr.push(_obj);
          })
          that.setData({
            cookerArr,
          })
        }
      }
    })
  },
})